/*
 * lvd.c
 *
 * realize LVD funtion.
 *
 * Copyright (C) 2024 Sinh Micro, Inc.
 * Subject to the GNU Public License, version 2.
 *
 * Author: lixiang<lixiang@sinhmicro.com>
 * 
 * Encoding format: GB2312
 * Version: v1.2.2
 * Date: 2024-11-05
 */

#include "hal/inc/hal-regs.h"
#include "hal/inc/types.h"
#include "hal/inc/power.h"
#include "hal/inc/debug.h"

#include "ec_app_config.h"
#include "lvd.h"
#include "heat.h"
#include "power_manage.h"
#include "sys_event.h"
#include "battery.h"

bool lvd_is_sys_valid_wakesrc(void)
{
    uint8_t io_wake;

    /* altimer or vin */
    if (POWER_IS_ATIMER_WAKEUP() || POWER_IS_VIN_WAKEUP()) {
        return true;
    }

#if (CONFIG_MIC_TYPE > 0)
    /* cap mic */
    if (TSSTAT & 0x10) {
        return true;
    }
#endif

    io_wake = 0;
    /* check IO wake config only*/
#if ((CONFIG_POWER_SLP_WK_0 & 0x00FF) != 0x00FF)
    if (power_check_and_clear_sleep_reason(true, CONFIG_POWER_SLP_WK_0 & 0x00ff)) {
        io_wake |= 0x01;
    }
#endif

#if ((CONFIG_POWER_SLP_WK_1 & 0x00FF) != 0x00FF)
    if (power_check_and_clear_sleep_reason(true, CONFIG_POWER_SLP_WK_1 & 0x00ff)) {
        io_wake |= 0x02;
    }
#endif

#if ((CONFIG_POWER_SLP_WK_2 & 0x00FF) != 0x00FF)
    if (power_check_and_clear_sleep_reason(true, CONFIG_POWER_SLP_WK_2 & 0x00ff)) {
        io_wake |= 0x04;
    }
#endif

#if ((CONFIG_POWER_SLP_WK_3 & 0x00FF) != 0x00FF)
    if (power_check_and_clear_sleep_reason(true, CONFIG_POWER_SLP_WK_3 & 0x00ff)) {
        io_wake |= 0x08;
    }
#endif

#if ((CONFIG_POWER_SLP_WK_4 & 0x00FF) != 0x00FF)
    if (power_check_and_clear_sleep_reason(true, CONFIG_POWER_SLP_WK_4 & 0x00ff)) {
        io_wake |= 0x10;
    }
#endif

    return (!!io_wake);
}

void lvd_handle_10ms(void)
{
    static idata uint8_t lvd_cnt;

    EINTSTAT = 0x04;

    if (heating_flag) {
        if (EINTSTAT & 0x04) {
            EINTSTAT = 0x04;
            lvd_cnt++;
        } else {
            lvd_cnt = 0;
        }

        if (lvd_cnt == 3) {
            lvd_cnt = 0;
            debug_print("lvd heat\n", 0);
            heat_stop();
            event_state_mask |= EVENT_STATE_HEAT_LOW_BAT;
            battery_force_low_cap();
        }
    } else {
        lvd_cnt = 0;
    }
}